import requests
from lxml import etree
import time

# list 转 string 函数
def convert_list_to_string(list_data):
        temp = ""
        for i in range(len(list_data)):
            temp += list_data[i]
            if(i!=len(list_data)-1):
                temp+=" "
        return temp

# 主方法
def fetch_match_data(mid, cid):
    start_time = time.time()  # 记录开始时间
    
    # 亚让页面
    url = f'http://vip.titan007.com/changeDetail/3in1Odds.aspx?id={mid}&companyid={cid}&l=0'

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.562.400 QQBrowser/19.6.6725.400',
        'Referer': 'http://vip.titan007.com/'
    }
    # 发送请求
    response = requests.get(url, headers=headers)
    # 设置编码格式 utf-8 GBK
    # response.encoding = 'GBK'

    # 处理结果

    html_tree = etree.HTML(response.text)

    # 判断是否继续爬取
    a = html_tree.xpath('//table//tr[2]//text()')
    ab = [text.strip() for text in a if text.strip()]
    if len(ab)==0:
        print('该比赛没有三合一数据！')
        return
    
    # 进球时间
    # 1. 获取所有包含红色背景单元格的行
    red_rows = html_tree.xpath('//div[3]/table//tr[td[@style="background-color:red;color:White;"]]')
    red_items = []
    for row in red_rows:
        jinqiu_time_temp = row.xpath('td[1]/text()')[0]
        if jinqiu_time_temp == '中场':
            jinqiu_time_temp = '45'
        score = row.xpath('td[2]/text()')[0].strip()  # 提取比分（如1-0）
        red_items.append({"jinqiu_time": jinqiu_time_temp, "score": score})
    red_items = red_items[::-1]  # 使用切片方式逆序
    # 2. 标记无效行（核心逻辑）
    invalid_indices = set()  # 存储需要排除的行索引
    
    # 辅助函数：解析比分为（主队进球，客队进球）
    def parse_score(s):
        try:
            home, away = map(int, s.split("-"))
            return home, away
        except:
            return (0, 0)  # 异常格式默认0-0

    # 遍历所有红色行，标记“进球-撤销”对
    for i in range(len(red_items)):
        # 若当前行已被标记为无效，跳过
        if i in invalid_indices:
            continue
        
        curr_home, curr_away = parse_score(red_items[i]["score"])
        curr_total = curr_home + curr_away
        
        # 检查后续所有行，是否存在“撤销当前进球”的记录
        for j in range(i + 1, len(red_items)):
            next_home, next_away = parse_score(red_items[j]["score"])
            next_total = next_home + next_away
            
            # 若后续行总进球数 < 当前行 → 形成“进球-撤销”对，两者均无效
            if next_total < curr_total:
                invalid_indices.add(i)  # 标记当前进球行为无效
                invalid_indices.add(j)  # 标记撤销行为无效
                break  # 找到一对后，无需继续检查后续行

    # 3. 提取有效时间（排除所有标记为无效的行）
    valid_times = [
        item["jinqiu_time"] 
        for idx, item in enumerate(red_items) 
        if idx not in invalid_indices 
        and (parse_score(item["score"])[0] + parse_score(item["score"])[1] > 0)  # 排除0-0的异常行
    ]

    goal_time = ""
    for i in range(len(valid_times)):
        goal_time += valid_times[i]
        if(i!=len(valid_times)-1):
            goal_time+="'/"
        else:
            goal_time+="'"

    # 终盘
    closing_session_text = html_tree.xpath('//div[3]/table//tr[td[@class="hg_red"]][1]/td[position()>=3 and position()<=5]//text()')
    closing_session_text = convert_list_to_string(closing_session_text)

    # 中场让球盘
    midfield = html_tree.xpath('//div[3]/table//tr[td[1][text()="中场"]][1]/td[position()>=3 and position()<=5]//text()')
    if len(midfield) != 0:
        i = 2
        while i <= 10:  # 设置一个合理的上限避免无限循环
            if midfield and '封' in midfield:
                midfield = html_tree.xpath(f'//div[3]/table//tr[td[1][text()="中场"]][{i}]/td[position()>=3 and position()<=5]//text()')
                i += 1
            else:
                break
    else:
        midfield = html_tree.xpath('//div[3]/table//tr[td[1][text()<=45]][1]/td[position()>=3 and position()<=5]//text()')
        j = 2
        while j <= 10:  # 设置一个合理的上限避免无限循环
            if midfield and '封' in midfield:
                midfield = html_tree.xpath(f'//div[3]/table//tr[td[1][text()<=45]][{j}]/td[position()>=3 and position()<=5]//text()')
                j += 1
            else:
                break
    midfield = convert_list_to_string(midfield)
    print(midfield)

    # 大小盘
    big_small_texts = html_tree.xpath('//div[4]/table//tr[td[@class="hg_red"]][1]/td[4]//text()')
    big_small_texts = convert_list_to_string(big_small_texts)

    #中场大小盘
    mid_big_small_texts = html_tree.xpath('//div[4]/table//tr[td[1][text()="中场"]][1]/td[4]//text()')
    if len(mid_big_small_texts) != 0:
        i = 2
        while i <= 10:  # 设置一个合理的上限避免无限循环
            if midfield and '封' in midfield:
                mid_big_small_texts = html_tree.xpath(f'//div[4]/table//tr[td[1][text()="中场"]][{i}]/td[4]//text()')
                i += 1
            else:
                break
    else:
        mid_big_small_texts = html_tree.xpath('//div[4]/table//tr[td[1][text()<=45]][1]/td[4]//text()')
        j = 2
        while j <= 10:  # 设置一个合理的上限避免无限循环
            if midfield and '封' in midfield:
                midfield = html_tree.xpath(f'//div[4]/table//tr[td[1][text()<=45]][{j}]/td[4]//text()')
                j += 1
            else:
                break
    mid_big_small_texts = convert_list_to_string(mid_big_small_texts)
    print(mid_big_small_texts)

    # tableContent左
    left_table_elements = html_tree.xpath('//div[3]/table')
    left_table_html = etree.tostring(left_table_elements[0], encoding='unicode', pretty_print=True)
    # 去掉&#13;和其他不必要的字符
    left_table_html = left_table_html.replace('&#13;', '').replace('\r', '')

    # tableContent中
    middle_table_elements = html_tree.xpath('//div[4]/table')
    middle_table_html = etree.tostring(middle_table_elements[0], encoding='unicode', pretty_print=True)
    # 去掉&#13;和其他字符
    middle_table_html = middle_table_html.replace('&#13;', '').replace('\r', '')

    # tableContent右
    right_table_elements = html_tree.xpath('//div[5]/table')
    right_table_html = etree.tostring(right_table_elements[0], encoding='unicode', pretty_print=True)
    # 去掉&#13;和其他字符
    right_table_html = right_table_html.replace('&#13;', '').replace('\r', '')

    # 追加写入html文件
    # with open('yarang.html', 'a', encoding='utf-8') as f:
    #     f.write(left_table_html)
    #     f.write(middle_table_html)
    #     f.write(right_table_html)

    end_time = time.time()  # 记录结束时间
    execution_time = end_time - start_time  # 计算执行时间
    print(f"三合一页面的运行时间: {execution_time:.2f} 秒")  # 打印执行时间

    # 进球时间，终盘，中场让球盘，大小盘，中场大小盘，table左中右
    result = [goal_time,closing_session_text,midfield,big_small_texts,mid_big_small_texts,left_table_html,middle_table_html,right_table_html]
    # result = [mid_big_small_texts]
    return result

if __name__ == '__main__':
    mid = 2828610
    cid = 3
    result = fetch_match_data(mid, cid)
    # 写入json文件
    import json
    with open('detail.json', 'w', encoding='utf-8') as f:
        json.dump(result, f, ensure_ascii=False, indent=4)